package utils

import (
	comm "com.wangzhumo.lottery/common"
	"com.wangzhumo.lottery/datasource"
	"fmt"
	"log"
	"math"
	"time"
)

// 用户抽奖次数 - 需要准确的值

func init() {
	resetGroupUserList()
}

func resetGroupUserList() {
	log.Println("lucky_user_count resetGroupUserList clear -- start")
	redisConn := datasource.InstanceRedis()
	for i := 0; i < ipFrameSize; i++ {
		// 将两个hash表都删除
		key := fmt.Sprintf("day_user_%d", i)
		// 删除key
		_, _ = redisConn.Do("DEL", key)
	}
	log.Println("lucky_user_count resetGroupUserList clear -- start")

	// 启动下一个定时器，执行定时清除
	duration := comm.NextDayDuration()
	// 计划
	time.AfterFunc(duration, resetGroupUserList)
}

const userFrameSize = 2

// IncrUserLuckyNum 增加用户抽将次数 - 原子性的增加
func IncrUserLuckyNum(uid int) int64 {
	i := uid % userFrameSize
	// 确定key，通过上面的散列结果
	key := fmt.Sprintf("day_user_%d", i)
	redisConn := datasource.InstanceRedis()
	// 递增这个用户的数据 1
	replay, err := redisConn.Do("HINCRBY", key, uid, 1)
	if err != nil {
		log.Println("IncrUserLuckyNum key = ", key, " ,uid = ", uid, err)
		return math.MaxInt32
	}
	return replay.(int64)
}

// InitUserLuckyNum 初始化 - 获取数据库数据为初始值
func InitUserLuckyNum(uid int, num int) {
	if num <= 1 {
		return
	}
	i := uid % userFrameSize
	// 确定key，通过上面的散列结果
	key := fmt.Sprintf("day_user_%d", i)
	redisConn := datasource.InstanceRedis()
	_, err := redisConn.Do("HSET", key, uid, num)
	if err != nil {
		log.Println("InitUserLuckyNum key = ", key, " ,uid = ", uid, err)
	}
}
